<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>5-13 马赛克1</title>
</head>

<body>
  <canvas id="c" width="700" height="300" style="border: 1px solid #ccc;"></canvas>

  <script>
    // 原文出处 http://www.ptbird.cn/canvas-img-ma.html
    const context = document.getElementById('c')
    const ctx = context.getContext('2d')

    const img = new Image()
    img.src = '../images/dog.jpg'
    img.crossOrigin = ''

    img.onload = () => {
      ctx.drawImage(img, 10, 10)

      let imgData = ctx.getImageData(10, 10, img.width, img.height)

      let num = 10
      let imgWidthStep = imgData.width / num
      let imgHeightStep = imgData.height / num

      for (let i = 0; i < imgWidthStep; i++) {
        for (let j = 0; j < imgHeightStep; j++) {
          let color = computedColor(imgData, (i + 1) * num, j * num)
          for (let k = 0; k < num; k++) {
            for (let l = 0; l < num; l++) {
              setImg(imgData, i * 10 + l, j * 10 + k, color)
            }
          }
        }
      }
      ctx.putImageData(imgData, imgData.width + 30, 10)
    }

    // 计算颜色值
    function computedColor(imgData, x, y) {
      const { width, data } = imgData
      const color = []

      color[0] = data[(y * width + x) * 4 + 0] // r
      color[1] = data[(y * width + x) * 4 + 1] // g
      color[2] = data[(y * width + x) * 4 + 2] // b
      color[3] = data[(y * width + x) * 4 + 3] // a
      return color
    }

    // 设置颜色
    function setImg(imgData, x, y, color) {
      const { width, data } = imgData
      data[(y * width + x) * 4 + 0] = color[0] // r
      data[(y * width + x) * 4 + 1] = color[1] // g
      data[(y * width + x) * 4 + 2] = color[2] // b
      data[(y * width + x) * 4 + 3] = color[3] // a
    }
  </script>
</body>

</html>